package com.weituotian.system.controller;

import com.weituotian.core.controller.BaseController;
import com.weituotian.core.exception.ServiceException;
import com.weituotian.core.result.JsTreeNode;
import com.weituotian.core.result.Result;
import com.weituotian.core.utils.PageInfo;
import com.weituotian.system.entity.Menu;
import com.weituotian.system.entity.Resource;
import com.weituotian.system.entity.User;
import com.weituotian.system.entity.enums.OpenState;
import com.weituotian.system.entity.enums.UserType;
import com.weituotian.system.entity.vo.MenuVo;
import com.weituotian.system.service.IMenuService;
import com.weituotian.system.service.IResourceService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * 菜单控制器
 * Created by ange on 2017/2/3.
 */
@Controller
@RequestMapping("${systemPath}/menu")
public class MenuController extends BaseController {

    private final IMenuService menuService;

    private final IResourceService resourceService;

    @Autowired
    public MenuController(IMenuService menuService, IResourceService resourceService) {
        this.menuService = menuService;
        this.resourceService = resourceService;
    }

    @ModelAttribute
    public void initUrl(Model model) {
        String contextPath = this.getContextPath();
        model.addAttribute("list_url", contextPath + systemPath + "/menu/ajaxlist");
        model.addAttribute("tree_url", contextPath + systemPath + "/menu/ajaxtree");
        model.addAttribute("edit_url", contextPath + systemPath + "/menu/edit");
        model.addAttribute("add_url", contextPath + systemPath + "/menu/add");
        model.addAttribute("delete_url", contextPath + systemPath + "/menu/delete");

        model.addAttribute("resources_url", contextPath + systemPath + "/role/grant");
        model.addAttribute("icon_url", contextPath + systemPath + "/menu/selecticon");
    }

    @RequestMapping(value = "/ajaxlist", produces = "application/json; charset=utf-8")
    @ResponseBody
    public Result ajaxList(Integer offset, Integer limit, String sort, String order) {
        PageInfo<MenuVo> pageInfo = new PageInfo<MenuVo>(1, limit);

        //这里的offset会覆盖pageinfo构造函数中根据当前页数page计算的offset
        offset = offset == null ? 0 : offset;
        pageInfo.setFrom(offset);

        //条件
        pageInfo.setCondition(getSearchMap());

        //排序
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            pageInfo.addSort(sort, order);
        }

        //返回的json
        Result result = new Result();

        menuService.findPageMenuVo(pageInfo);


//        TableResult tableResult = new TableResult(pageInfo.getTotal(), pageInfo.getList());

        result.setSuccess(true);
        result.setObj(pageInfo);
        result.setMsg("获取成功");

        return result;

//        model.addAttribute("pageinfo", pageInfo);
//        return "resource/index";
    }

    @RequestMapping(value = "/ajaxtree", produces = "application/json; charset=utf-8")
    @ResponseBody
    public Result ajaxPage(String pid) {

//        List<ResourceVo> all = resourceService.getResourceJsTree(pid);
        List<JsTreeNode> nodes;
        Result result = new Result();
        try {
            if (pid.equals("#")) {
                //根节点
                /*JsTreeNode rootNode = menuService.findJsTreeNode(0);
                nodes = menuService.findJsTreeNodeByPid(0);*/

                //节点状态[默认展开]
                /*JsTreeNode.State state = rootNode.new State();
                state.opened = true;
                rootNode.setState(state);
                rootNode.setChildren(nodes);
                result.setObj(rootNode);*/

                nodes = menuService.findJsTreeRootNodes();
                JsTreeNode node = nodes.get(0);
                JsTreeNode.State state = node.new State();
                state.opened = true;
                node.setState(state);//默认第一个展开
                result.setObj(nodes);

            } else {
                nodes = menuService.findJsTreeNodeByPid(Integer.valueOf(pid));
                //否则返回列表
                result.setObj(nodes);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }

        result.setSuccess(true);
        result.setMsg("获取资源列表成功");
        return result;
    }

    @RequestMapping(value = "/list")
    public String index(Model model) {

        //资源类型
//        List<ResourceType> resTypes = resourceTypeService.getAllResourceTypeList();
//        model.addAttribute("resTypes", resTypes);

        model.addAttribute("pageName", "菜单列表");
        return "system/menu/index";
    }

    /**
     * 编辑页面
     *
     * @return
     */
    @RequestMapping(value = "/edit")
    public String edit(Integer id, Model model) {
        Menu menu = menuService.findById(id);

        model.addAttribute("openStatus", OpenState.values());

        model.addAttribute("menu", menu);
        model.addAttribute("form_url", this.getContextPath() + systemPath + "/menu/doedit");
        model.addAttribute("action", "edit");

        model.addAttribute("pageName", "菜单编辑");
//        return systemPath + "/menu/edit";
        return "system/menu/edit";
    }

    /**
     * 处理编辑
     *
     * @return
     */
    @RequestMapping(value = "/doedit", produces = "application/json; charset=utf-8")
    @ResponseBody
    public Object doedit(Menu menu, Integer pid, Integer resource_id) {
        try {
            //更新用户,封装到了一个事务中
            menuService.updateMenu(menu, pid, resource_id);
        } catch (ServiceException e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }
        return renderSuccess("修改成功");
    }

    /**
     * 增加页面
     *
     * @param model
     * @return
     */
    @RequestMapping("/add")
    public String add(Integer pid, Model model) {

        Menu menu = new Menu();
        menu.setSeq((short) 1);
        menu.setStatus(OpenState.OPEN);

        if (pid != null) {
            Menu parent = menuService.findById(pid);
            menu.setParent(parent);
        }

        model.addAttribute("openStatus", OpenState.values());

        model.addAttribute("menu", menu);
        model.addAttribute("form_url", this.getContextPath() + systemPath + "/menu/doadd");
        model.addAttribute("action", "add");

        model.addAttribute("pageName", "菜单新增");
        return "system/menu/edit";
    }

    /**
     * 处理增加
     *
     * @param role
     * @return
     */
    @RequestMapping(value = "/doadd", produces = "application/json; charset=utf-8")
    @ResponseBody
    public Object doadd(Menu menu, Integer pid, Integer resource_id) {
        try {
            if (resource_id != null) {
                Resource resource = resourceService.findById(resource_id);
                menu.setResource(resource);
            }
            if (pid != null) {
                Menu pMenu = menuService.findById(pid);
                menu.setParent(pMenu);
            }
            menuService.add(menu);
        } catch (Exception e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }
        return renderSuccess("增加成功!");
    }

    /**
     * 批量删除
     *
     * @param ids ids
     * @return
     */
    @RequestMapping(value = "/delete", produces = "application/json; charset=utf-8")
    @ResponseBody
    public Object delete(@RequestParam(value = "ids[]") Integer[] ids) {
        try {
            menuService.deleteBatch(ids);
        } catch (Exception e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }
        return renderSuccess("删除成功!");
    }

    /**
     * 选择图标
     *
     * @return
     */
    @RequestMapping("/selecticon")
    public String selectIcon(Model model) {
        model.addAttribute("pageName", "选择图标");
        return "system/menu/selecticon";
    }

    /**
     * ajax获取菜单
     *
     * @return
     */
    @RequestMapping(value = "/getmenu", produces = "application/json; charset=utf-8")
    @ResponseBody
    public Object menu() {
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
        Result result = new Result();

        if (user != null) {

            List<MenuVo> menuVos;
            if (user.getUserType() == UserType.TOPADMIN) {//最高管理员享有所有菜单
                menuVos = menuService.findAllMenuVo();
            } else {
                menuVos = menuService.findUserMenuVo();
            }
            //改为js生成树,后台不再生成树
            //List<Menu> tree = getMenuTree(user);
            /*List<Resource> resources;
            if (user.getUsertype() == 1) {
                resources = resourceService.findMenusAll();
            } else {
                resources = resourceService.findMenusByUserId(user.getId());
            }

            resourceService.AddContextPath(resources, this.getContextPath());*/

            //增加contextpath
            String contextPath = this.getContextPath();
            for (MenuVo menuVo : menuVos) {
                menuVo.setResourceUrl(contextPath + menuVo.getResourceUrl());
            }

            result.setSuccess(true);
            result.setObj(menuVos);
            result.setMsg("获取菜单成功");

        } else {
            result.setSuccess(false);
            result.setMsg("出现错误,当前用户不存在");
        }
        return result;
    }
}
